import app from "../server"
import serverConfig from '../config';
import glossary from "../util/glossary"
import getTopK from "../util/topKheap"
import SearchByTime from "../util/searchByTime"
import SearchByIntelligence from "../util/searchByIntelligence"
import redis from "redis"
import searchSchema from "../models/searchModel"
import {kgAdapter} from "../util/kgAdapter"

const client = redis.createClient(serverConfig.redisPort, serverConfig.redisURL);
client.on("error",function(err) {
  console.log(err);
})

export function keywordMatching(req, res){
  let { keyword } = req.query;
  const trie = app.get("trie")
  const map = {};
  trie.preTraversal(function (node, str) {
    if (str.indexOf(keyword) === 0 && node.isEnd) {
      map[str] = node.numEnd
    }
  })
  let queryArray = [];
  for (let i in map){
    queryArray.push(i)
  }
  client.mget(queryArray,(err,reply)=>{
    if(err){
      res.status(500).send({data: [{key:'无',num:0}],msg:glossary["internalError"]})
    }else{
      let heap=[];
      let responseKeyValue = [];
      for (let i =0;i<reply.length;i++){
        if(reply[i]==null){
          reply[i] = 1;
        }else{
          reply[i]++;
        }
        heap.push({key:queryArray[i],num:reply[i]})
        responseKeyValue.push(queryArray[i])
        responseKeyValue.push(reply[i])
      }
      heap = getTopK(heap,5)
      client.mset(responseKeyValue,(e,r)=>{
        if(e){
          res.status(500).send({data:[{key:'无',num:0}],msg:glossary["internalError"]})
        }else{
          res.json({data:heap,msg:glossary["success"]})
        }
      })
    }
  })
}
// url query格式
// search/searchDocument?searchType:{'intelligence','time'}
// &searchContent:{'title','content','all'}
// &searchTime:{'all','year','month','week','day'}
// &keyword:{'xxxx'}
// &pageNum: int
// &pageSize: int 默认5
// 开始在数据库crud
export function searchByType(req,res){
  let { searchType,keyword } = req.query;
  if(keyword===''){
    res.json({data:{},msg:glossary.success})
  }else if(searchType==='time'){
      let search_by_time = new SearchByTime();
      search_by_time.choose(req,res);
      return;
  }else if(searchType==='intelligence'){
      let search_by_intelligence = new SearchByIntelligence();
      search_by_intelligence.choose(req,res);
      return;
  }else{
    res.status(500).send({data:{},msg:glossary.badRequest})
  }
}

export function addClickNum(req,res){
  let { id } = req.query
  console.log(id)
  searchSchema.findOne({_id: id},(err1,doc)=>{
    if(err1){
      res.status(500).send({data:{},msg:glossary.badRequest})
      return;
    }
    searchSchema.update({_id:id},{clickNum:doc.clickNum+1},(err2,d)=>{
      if(err2){
        res.status(500).send({data:{},msg:glossary.badRequest})
      }
      res.json({data:'about:blank',msg:glossary.success})
    })
  })
}

export function getFromTestKg(req,res){
  let { sentence }  = req.query;
  kgAdapter(serverConfig.kgName,sentence,res);
}




